package com.xqboss.apps.service.user;


import cn.hutool.core.bean.BeanUtil;
import com.xqboss.apps.domain.user.UserIdentityPermWrenchPresenter;
import com.xqboss.apps.vo.user.HotBeansGiveBeforeVo;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.constant.Constants;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.user.UserIdentityPermLidou;
import com.xqboss.apps.mapper.user.UserIdentityPermLidouMapper;

import java.util.Map;


/**
 * 力豆转赠配置(UserIdentityPermLidou)表服务实现类
 *
 * @author makejava
 * @since 2024-03-08 14:21:47
 */
@Service
public class UserIdentityPermLidouService extends ServiceImpl<UserIdentityPermLidouMapper, UserIdentityPermLidou> {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserIdentityService userIdentityService;

    /**
     * 用户权限信息
     * @param identityId
     * @param userId
     * @return
     */
    public HotBeansGiveBeforeVo userInfo(Long identityId, Long userId) {
        UserIdentityPermLidou entity = this.lambdaQuery()
                .eq(UserIdentityPermLidou::getIdentityId, identityId)
                .one();
        if (entity == null){
            throw new ServiceException("该身份没有配置力豆转赠权限");
        }
        HotBeansGiveBeforeVo vo = BeanUtil.copyProperties(entity, HotBeansGiveBeforeVo.class);
        // 从redis获取用户转增使用次数,如果没有 则为0
        Map<String, Integer> map = redisCache.getCacheMap(CacheConstants.USER_LIDOU_COUNT_ALL_KEY);
        // 使用次数
        Integer integer = map.get(userId.toString());
        if (integer == null) {// 用户当日没有进行过转增,使用次数应为0
            vo.setHitCount(0);
        } else {
            vo.setHitCount(integer);
        }
        return vo;
    }

    public Boolean getIsOpen(Long userId) {
        Long identityId = userIdentityService.getByUserId(userId).getId();
        UserIdentityPermLidou one = this.lambdaQuery().eq(UserIdentityPermLidou::getIdentityId, identityId).last("limit 1").one();
        return (one==null?0:one.getIsOpen())!=0;
    }
}
